package com.ld.wms.business.approve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.wms.business.approve.mapper.ApproveUserMapper;
import com.ld.wms.business.approve.mapper.MaterialExampleInventoryApproveMapper;
import com.ld.wms.business.approve.model.MaterialExampleInventoryApproveModel;
import com.ld.wms.business.approve.service.MaterialExampleInventoryApproveService;
import com.ld.wms.business.approve.service.MaterialExampleReceiveService;
import com.ld.wms.business.approve.vo.req.ApproveReqVo;
import com.ld.wms.business.approve.vo.req.MaterialExampleInventoryApproveReqVo;
import com.ld.wms.business.approve.vo.req.MaterialExampleReceiveReqVo;
import com.ld.wms.business.approve.vo.resp.ApproveUserRespVo;
import com.ld.wms.business.approve.vo.resp.MaterialExampleInventoryApproveRespVo;
import com.ld.wms.business.material.mapper.MaterialExampleInventoryMapper;
import com.ld.wms.business.material.model.MaterialExampleInventoryModel;
import com.ld.wms.business.material.service.MaterialExampleInventoryService;
import com.ld.wms.business.user.model.UserAccountModel;
import com.ld.wms.business.user.service.UserAccountService;
import com.ld.wms.common.vo.GeneratePageListVo;
import com.ld.wms.exception.BusinessException;
import com.ld.wms.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 物料实例库存审批列表 服务实现类
 * </p>
 *
 * @author wangfeng
 * @since 2025-04-15
 */
@Slf4j
@Service
public class MaterialExampleInventoryApproveServiceImpl extends ServiceImpl<MaterialExampleInventoryApproveMapper, MaterialExampleInventoryApproveModel> implements MaterialExampleInventoryApproveService {

    private final ReentrantLock lock = new ReentrantLock();

    @Autowired
    private MaterialExampleInventoryApproveMapper materialExampleInventoryApproveMapper;

    @Autowired
    private MaterialExampleInventoryService materialExampleInventoryService;

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private MaterialExampleReceiveService materialExampleReceiveService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private ApproveUserMapper approveUserMapper;

    @Autowired
    private MaterialExampleInventoryMapper materialExampleInventoryMapper;


    @Override
    @Transactional
    public void receiveApprove(MaterialExampleInventoryApproveReqVo reqVo) {
        lock.lock();
        try {
            // 查询是否重复申请
            QueryWrapper<MaterialExampleInventoryApproveModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(MaterialExampleInventoryApproveModel.MATERIAL_EXAMPLE_INVENTORY_ID, reqVo.getMaterialExampleInventoryId());
            MaterialExampleInventoryApproveModel materialExampleInventoryApproveModelDbInfo = materialExampleInventoryApproveMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(materialExampleInventoryApproveModelDbInfo)) {
                throw new BusinessException("不能重复申请同一个库存！");
            }

            Long currentUserAccountId = jwtUtils.getCurrentUserAccountId();
            Long materialExampleInventoryId = reqVo.getMaterialExampleInventoryId();
            MaterialExampleInventoryModel materialExampleInventoryModel = materialExampleInventoryService.getById(materialExampleInventoryId);
            MaterialExampleInventoryApproveModel materialExampleInventoryApproveModel = new MaterialExampleInventoryApproveModel();
            materialExampleInventoryApproveModel.setMaterialExampleInventoryId(materialExampleInventoryId);
            materialExampleInventoryApproveModel.setMaterialExampleId(materialExampleInventoryModel.getMaterialExampleId());
            materialExampleInventoryApproveModel.setApproveUserId(0L);
            materialExampleInventoryApproveModel.setStatus(0);
            materialExampleInventoryApproveModel.setCreateBy(currentUserAccountId);
            materialExampleInventoryApproveModel.setCreateTime(new Date());
            materialExampleInventoryApproveMapper.insert(materialExampleInventoryApproveModel);

            ApproveReqVo reqVo1 = new ApproveReqVo();
            reqVo1.setMaterialExampleInventoryApproveId(materialExampleInventoryApproveModel.getId());
            reqVo1.setApproveAction(0);
            reqVo1.setRemark("同意审批");
            approve(reqVo1);
            // 库存状态改成已出借
            materialExampleInventoryModel.setStatus(1);
            materialExampleInventoryMapper.updateById(materialExampleInventoryModel);
        } catch (Exception e) {
            log.error("equipmentCallBack error:", e);
            throw new BusinessException(e.getMessage());
        } finally {
            lock.unlock();// 确保释放锁
        }


    }

    @Override
    public GeneratePageListVo<MaterialExampleInventoryApproveRespVo> getPageList(Integer current, Integer size) {
        Long currentUserAccountId = jwtUtils.getCurrentUserAccountId();
        IPage<MaterialExampleInventoryApproveRespVo> iPage = new Page<>(current, size);
        IPage<MaterialExampleInventoryApproveRespVo> iPage1 = materialExampleInventoryApproveMapper.selectPageList(iPage, currentUserAccountId);
        Map<Long, UserAccountModel> allUserMap = userAccountService.getAllUserMap();
        for (MaterialExampleInventoryApproveRespVo record : iPage1.getRecords()) {
            if (record.getStatus() == 2 || record.getStatus() == 3 || record.getStatus() == 4) {
                continue;
            }
            UserAccountModel userAccountModel = allUserMap.get(record.getCreateBy());
            record.setUserAccountName(userAccountModel.getAccountName());
            if (currentUserAccountId.equals(record.getApproveUserId())) {
                record.setOperateButtonFlag(1);
            }
        }
        return new GeneratePageListVo<>(iPage1);
    }

    @Override
    public void approve(ApproveReqVo reqVo) {
        Long currentUserAccountId = jwtUtils.getCurrentUserAccountId();
        MaterialExampleInventoryApproveModel materialExampleInventoryApproveModel = materialExampleInventoryApproveMapper.selectById(reqVo.getMaterialExampleInventoryApproveId());
        materialExampleInventoryApproveModel.setUpdateBy(currentUserAccountId);
        materialExampleInventoryApproveModel.setUpdateTime(new Date());

        Long approveUserId = materialExampleInventoryApproveModel.getApproveUserId();
        Long materialExampleId = materialExampleInventoryApproveModel.getMaterialExampleId();
        // 判断是否拒绝,0通过，1拒绝
        if (reqVo.getApproveAction() == 1) {
            materialExampleInventoryApproveModel.setStatus(3);
            materialExampleInventoryApproveMapper.updateById(materialExampleInventoryApproveModel);
            return;
        }

        // 判断是否拒绝,0通过，1拒绝
        if (reqVo.getApproveAction() == 2) {
            materialExampleInventoryApproveModel.setStatus(4);
            materialExampleInventoryApproveMapper.updateById(materialExampleInventoryApproveModel);
            return;
        }

        if (reqVo.getApproveAction() == 0) {
            //查找是否有下一个审批人，如果没有直接通过，然后往领取列表加一条数据
            ApproveUserRespVo approveUserRespVo = approveUserMapper.selectByParentId(approveUserId);
            // 如果没有下 一级审核人直接审核通过
            if (ObjectUtils.isEmpty(approveUserRespVo) || approveUserId == 0) {
                // 领取列表新增一条数据
                MaterialExampleReceiveReqVo materialExampleReceiveReqVo = new MaterialExampleReceiveReqVo();
                materialExampleReceiveReqVo.setMaterialExampleInventoryId(materialExampleInventoryApproveModel.getMaterialExampleInventoryId());
                materialExampleReceiveReqVo.setUserAccountId(materialExampleInventoryApproveModel.getCreateBy());
                materialExampleReceiveReqVo.setStatus(0);
                materialExampleReceiveService.add(materialExampleReceiveReqVo);
                // 审批状态改成已通过
                materialExampleInventoryApproveModel.setStatus(2);
                materialExampleInventoryApproveMapper.updateById(materialExampleInventoryApproveModel);
            } else {
                materialExampleInventoryApproveModel.setApproveUserId(approveUserRespVo.getUserAccountId());
                materialExampleInventoryApproveMapper.updateById(materialExampleInventoryApproveModel);
            }
        }
    }
}
